package edu.csu.smartpark.util;

import org.apache.commons.lang3.StringEscapeUtils;
import org.thymeleaf.util.StringUtils;

import java.beans.PropertyEditorSupport;

/**
 * 类名称：StringEscapeEditor
 * 类描述：字符串转义
 * 创建人：CSUpipixia
 * 创建时间：2021/5/8 23:08
 *
 * @version v1.0
 */
public class StringEscapeEditor extends PropertyEditorSupport {
    private boolean escape;

    public StringEscapeEditor() {
        super();
    }

    public StringEscapeEditor(boolean escape) {
        super();
        this.escape = escape;
    }

    @Override
    public void setAsText(String text) {
        if (StringUtils.isEmpty(text)) {
            setValue(text);
        } else {
            String value = text;
            if (escape) {
                // 过滤字符串, 防止恶意HTML注入攻击
                value = StringEscapeUtils.escapeHtml4(value);
            }
            setValue(value);
        }
    }

    @Override
    public String getAsText() {
        Object value =getValue();
        return value!=null ? value.toString() : "";
    }
}
